#include "../include/e_rts_camera.h"

/* this class implements a rts camera
 * it would not be har to use it to
 * do a tpf or fps camera by changing
 * x or y values and locking cursor
 *
 */

///TODO: optimizie constructor and use key struct for handler

e_rts_camera::e_rts_camera()
{
    coordinate_x = 0;
    coordinate_y = 0;
    zoom_z = 1;

    fowards_now = 0;
    backwards_now = 0;
    left_now = 0;
    right_now = 0;
    in_now = 0;
    out_now = 0;

    angle_x = -20.0;
    angle_y = 45.0;

    //SDL_WM_GrabInput(SDL_GRAB_ON);
}

void e_rts_camera::update()
{
    zoom_z += (in_now + out_now) * 1;
    if(zoom_z < 1) zoom_z = 1;

    coordinate_y += .1 * (fowards_now + backwards_now) * zoom_z;
    coordinate_x += .1 * (right_now + left_now) * zoom_z;

    if(mouse_x < 30) coordinate_x += 0.003 * (30 - mouse_x) * zoom_z;
    if(mouse_x > 610) coordinate_x -= 0.003 * (mouse_x - 610) * zoom_z;
    if(mouse_y < 30) coordinate_y -= 0.003 * (30 - mouse_y) * zoom_z;
    if(mouse_y > 450) coordinate_y += 0.003 * (mouse_y - 450) * zoom_z;

    glTranslatef(coordinate_x, coordinate_y, 0.0f);
    glRotatef(angle_y, 0.0f, 0.0f, 1.0f);
    glTranslatef(0.0f, 0.0f, (1.0f - zoom_z));
    glRotatef(angle_x, cos(angle_y*(M_PI/180.0)), (0 - sin(angle_y*(M_PI/180.0))), 0.0f);
}

void e_rts_camera::handle_input(SDL_Event *event)
{
    if( event->type == SDL_MOUSEMOTION )
    {
        mouse_x = event->motion.x;
        mouse_y = event->motion.y;
    }

    if( event->type == SDL_MOUSEBUTTONDOWN )
    {
        switch( event->button.button )
        {
            case SDL_BUTTON_WHEELDOWN: zoom_z += .3; break;
            case SDL_BUTTON_WHEELUP: zoom_z -= .3; break;
            default: break;
        }
    }

    if( event->type == SDL_KEYDOWN )
    {
        switch( event->key.keysym.sym )
        {
            case SDLK_UP: fowards_now = -1; break;
            case SDLK_DOWN: backwards_now = 1; break;
            case SDLK_LEFT: left_now = 1; break;
            case SDLK_RIGHT: right_now = -1; break;
            case SDLK_e: out_now = 1; break;
            case SDLK_q: in_now = -1; break;
            case SDLK_ESCAPE: SDL_WM_GrabInput(SDL_GRAB_OFF); break;
            default: break;
        }
    }

    if( event->type == SDL_KEYUP )
    {
        switch( event->key.keysym.sym )
        {
            case SDLK_UP: fowards_now = 0; break;
            case SDLK_DOWN: backwards_now = 0; break;
            case SDLK_LEFT: left_now = 0; break;
            case SDLK_RIGHT: right_now = 0; break;
            case SDLK_e: out_now = 0; break;
            case SDLK_q: in_now = 0; break;
            default: break;
        }
    }
}
